import { objIDToObj, roomNameToObj } from "../baseTools"

const structureTool = {
    /**检查挂载在目标建筑上的creep，并清除失效的creep */
    updateObjCreepList: function (targetObj) {
        targetObj = objIDToObj(targetObj)
        let targetMemory = targetObj.room.memory['structure'][targetObj.structureType][targetObj.id]
        targetMemory = targetMemory.creeps.filter(creepName => {
            if (!Memory.creeps[creepName]) return false // 不存在内存
            if (Memory.creeps[creepName]['targetID'].length == 0) return false    // 不存在目标
            if (Memory.creeps[creepName]['targetID'][Memory.creeps[creepName]['targetID'].length - 1] != targetObj.id) return false // 存在的目标异常
        })
    },
    /**直接通过内存的方式检查挂载在目标建筑上的creep，并清除失效的creep;更节约CPU */
    updateObjCreepListByMemory: function (targetMemory) {
        targetMemory = targetMemory.creeps.filter(creepName => {
            if (!Memory.creeps[creepName]) return false // 不存在内存
            if (Memory.creeps[creepName]['targetID'].length == 0) return false    // 不存在目标
            if (Memory.creeps[creepName]['targetID'][Memory.creeps[creepName]['targetID'].length - 1] != targetObj.id) return false // 存在的目标异常
        })
    },
    /**清除挂载在目标建筑上的指定creep */
    deleteCreepInObjCreepList: function (targetObj, creepName) {
        targetObj = objIDToObj(targetObj)
        let creepList = targetObj.room.memory['structure'][targetObj.structureType][targetObj.id].creeps
        let index = creepList.indexOf(creepName)
        if (index != -1) creepList.splice(index, 1)
    },
    /**判断目标建筑是需要需能量
     * 1. 默认params={ resource : RESOURCE_ENERGY, limit : 1 }
     * 2. 根据limit阈值，小于该阈值返回true，大于等于该阈值返回false
     */
    isNeedEnergy: function (obj, params) {
        const { resource = RESOURCE_ENERGY, limit = 1 } = params
        obj = objIDToObj(obj)
        let result = { isNeed: false, needResource: resource }
        if (obj.store.getUsedCapacity(resource) / obj.store.getCapacity(resource) < limit) {
            result.isNeed = true
        }
        return result
    },
    /**判断房间内某一种creep是否满足数量需求，可以通过role，也可以通过role及其rule */
    isNeedCreep: function (room, creepRole, count, creepRule = null, creepTag = 'worker') {
        room = roomNameToObj(room)
        let result = { isNeed: false, currentAmount: 0, expectAmount: count }
        if (!creepRule) {
            if (room.memory.creeps[creepTag][creepRole].length < count) result.isNeed = true
            result.currentAmount = room.memory.creeps[creepTag][creepRole].length
        } else {
            // 如果需要对应身体部件role下对应rule的creep数量，则需要对creepTaskType进行详细规定
            let creeps = room.memory.creeps[creepTag][creepRole].slice()
            let creepAmount = creeps.filter(creepName => Memory.creeps[creepName].rule == creepRule).length
            if (creepAmount < count) result.isNeed = true
            result.currentAmount = creepAmount
        }
        return result
    }
}
export default structureTool